import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAppStore = defineStore('app', () => {
  const loading = ref(false)
  const theme = ref<'light' | 'dark'>('light')
  const sidebar = ref({
    opened: true,
    withoutAnimation: false
  })
  const device = ref<'desktop' | 'mobile'>('desktop')
  
  const setLoading = (value: boolean) => {
    loading.value = value
  }

  const toggleTheme = () => {
    theme.value = theme.value === 'light' ? 'dark' : 'light'
    document.documentElement.setAttribute('data-theme', theme.value)
  }

  const setTheme = (newTheme: 'light' | 'dark') => {
    theme.value = newTheme
    document.documentElement.setAttribute('data-theme', newTheme)
  }

  const toggleSidebar = () => {
    sidebar.value.opened = !sidebar.value.opened
  }

  const closeSidebar = (withoutAnimation: boolean = false) => {
    sidebar.value.opened = false
    sidebar.value.withoutAnimation = withoutAnimation
  }

  const setDevice = (deviceType: 'desktop' | 'mobile') => {
    device.value = deviceType
  }

  const initialize = async () => {
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | null
    if (savedTheme) {
      setTheme(savedTheme)
    }

    const handleResize = () => {
      const isMobile = window.innerWidth < 768
      setDevice(isMobile ? 'mobile' : 'desktop')
      
      if (isMobile && sidebar.value.opened) {
        closeSidebar(true)
      }
    }

    handleResize()
    window.addEventListener('resize', handleResize)
  }

  return {
    loading,
    theme,
    sidebar,
    device,
    setLoading,
    toggleTheme,
    setTheme,
    toggleSidebar,
    closeSidebar,
    setDevice,
    initialize
  }
})